//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web.UI.WebControls;

using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.Controls;

namespace CommunityServer.Blogs.Controls
{
    /// <summary>
    /// Summary description for EntryView.
    /// </summary>
    public class EntryView : WeblogThemedControl
    {
        public EntryView():base()
        {
		
        }

        private IText EntryTitle = null;
        private IText EntryBody = null;
        private IText EntryDesc = null;
		private HyperLink AuthorLink = null;
		private HyperLink EditLink = null;
		private BlogRatePost Ratings = null;
        private CategoryTagControl Tags = null;
        private DownloadAttachmentLink Attachment = null;
		private TrackbackMarkUp tb = null;
		private InlineTagEditorPanel InlineTagEditorPanel = null;
        
		private bool controlHasBound = false;
        

        protected override void AttachChildControls()
        {
            EntryTitle = FindText( "EntryTitle" );
            EntryBody = FindText( "EntryBody" );
            EntryDesc = FindText( "EntryDesc" );
			AuthorLink = FindControl( "AuthorLink" ) as HyperLink;
			EditLink = FindControl( "EditLink" ) as HyperLink;
			Ratings = FindControl("Ratings") as BlogRatePost;
            Tags = FindControl("Tags") as CategoryTagControl;
            Attachment = FindControl( "Attachment" ) as DownloadAttachmentLink;
			InlineTagEditorPanel = FindControl("InlineTagEditorPanel") as InlineTagEditorPanel;

			tb = new TrackbackMarkUp();

        }

        private WeblogPost _dataSource;
        
        /// <summary>
        /// Property DataSource (object)
        /// </summary>
        public WeblogPost DataSource
        {
            get
            {  return this._dataSource; }
            set
            {  this._dataSource = value; }
        }

		protected bool CanUserView(WeblogPost post)
		{
			//Always validate the sectionid
			if(post.SectionID != CurrentWeblog.SectionID)
				Globals.Return404(Context);

            if(!Permissions.ValidatePermissions(CurrentWeblog,Permission.Post,this.CurrentUser))
            {
                if(!post.IsApproved ||  post.PostDate > DateTime.Now)
                    Globals.Return404(Context);
            }

            return true;
			
		}

        public override void DataBind()
        {
            base.DataBind();
			CSContext context = CSContext.Current;

            if(DataSource != null)
            {
                //make sure we only render posts where they are supposed to be
                if(CanUserView(DataSource)) 
                {
                    EntryTitle.Text = DataSource.Subject;
                    EntryBody.Text = DataSource.RenderedBody(PostTarget.Web);
                    EntryDesc.Text = DataSource.UserTime.ToString(ThemeConfig.DateFormat);

                    if(DataSource.HasCategories)
                        Head.AddMetaTag("keywords", string.Join(",", DataSource.Categories), Context );

                    string excerpt = null;
                    if(DataSource.HasExcerpt)
                        excerpt = DataSource.Excerpt;
                    else
                        excerpt = DataSource.RenderedBody(PostTarget.Web);

                    Head.AddMetaTag("description", Globals.HtmlEncode(Formatter.RemoveHtml(excerpt,250).Trim()),Context);

                    if(this.CurrentWeblog.EnableRss)
                    {
						bool isAvailableToPublic = Permissions.ValidatePermissions(this.CurrentWeblog, Permission.View, Users.GetAnonymousUser(true));

						if (isAvailableToPublic)
							Head.AddRssAutoDiscovery(DataSource.Subject + " Comment RSS", Globals.FullPath(BlogUrls.Instance().CommentRss(this.CurrentWeblog.ApplicationKey, DataSource.PostID)), Context);
						else if (context.SiteSettings.EnableSecureSyndication)
							Head.AddRssAutoDiscovery(DataSource.Subject + " Comment RSS", Globals.FullPath(SiteUrls.FormatUrlWithUserNameToken(BlogUrls.Instance().CommentRss(this.CurrentWeblog.ApplicationKey, DataSource.PostID), context.User, true)), Context);
                    }

					if(EditLink != null)
					{
						if(Permissions.ValidatePermissions(this.CurrentWeblog,Permission.Post,this.CurrentUser))
						{
							EditLink.NavigateUrl = BlogUrls.Instance().PostEditor(this.CurrentWeblog.SectionID, DataSource.PostID);
							EditLink.Text = ResourceManager.GetString("Edit");
							EditLink.ToolTip = ResourceManager.GetString("Weblog_EntryList_Edit");
							EditLink.Visible = true;
						}
						else
						{
							EditLink.Visible = false;
						}
					}


                    if(Attachment != null && DataSource.HasAttachment)
                    {
                        Attachment.DataSource = DataSource.Attachment;
                        Attachment.DataBind();
                    }

					if (InlineTagEditorPanel != null)
					{
						InlineTagEditorPanel.PostID = DataSource.PostID;
						InlineTagEditorPanel.SelectedTags = DataSource.Categories;
					}

                    if(CurrentWeblog.ValidateRatings(DataSource))
                    {
                        Ratings.Visible = true;
                        Ratings.Post = DataSource;
                    }
                    else
                    {
                        Ratings.Visible = false;
                    }

                    if(AuthorLink != null)
                    {
						AuthorLink.Text = DataSource.DisplayName;
						
						if (!Globals.IsNullorEmpty(DataSource.SubmittedUserName))
                        {
                            AuthorLink.NavigateUrl = DataSource.GetExtendedAttribute("channel_link");
                            AuthorLink.Target = "new";
                        }
                        else
                        {
                            AuthorLink.NavigateUrl = Globals.GetSiteUrls().UserProfile(DataSource.AuthorID);
                        }
                    }

                    if(Tags != null)
                    {
                        Tags.DataSource = WeblogPosts.GetCategoryTags(this.DataSource);
                        Tags.DataBind();
                    }

                    Views.AddWebCount(DataSource.PostID);

                    
					tb.Title = DataSource.Subject;
                    tb.PermaLink = BlogUrls.Instance().Post(DataSource,CurrentWeblog);
                    tb.PingUrl = BlogUrls.Instance().TrackbackPingUrl(CurrentWeblog.ApplicationKey, DataSource.PostID);
						
					if(!controlHasBound)
						this.Controls.Add(tb);
					
					controlHasBound = true;
                }
                else
                {
                    Globals.Return404(Context);
                }
            }
        }

    }
}
